var util = require('../../utils/util.js');
var wxUtil = require('../../utils/wxUtil.js');
var ajax = require('../../utils/ajax.js');
var WxParse = require('../../utils/wxParse/wxParse.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var Pagination = require('../../common/pagination/index.js');
var ShareActionSheet = require('../../components/shareActionSheet/index.js');
var app = getApp();
var sliderWidth = 126; // 需要设置slider的宽度，用于计算中间位置

Page(common.extendPage(PageBase, {
    data: {
        dataLoaded: false,
        winHei: 0,
        swiperHei: 0,
        curSwiperIndex: 0,

        tabs: ["出刀记录", "总排行榜"],
        activeIndex: 0,
        sliderOffset: 0,
        sliderLeft: 0,
        sliderWidth,

        page1: {
            nextPageLoading: false,
            pageLoadedAll: false,
        },
        page2: {
            nextPageLoading: false,
            pageLoadedAll: false,
        },

        list: [],
        ranks: [],
        records: [],

        isShowPanel: false,
    },

    onShareAppMessage: function() {
        var {
            haggleId,
            cutId
        } = this.data;
        var {
            actInfo
        } = this.data;

        return {
            title: actInfo.title,
            path: `pages/cut/index?haggleId=${haggleId}&cutId=${cutId}`,
        }
    },

    onPullDownRefresh() {
        this._init();
    },

    onLoad: function(options) {
        var {
            haggleId,
            cutId
        } = util.parseOptions(options);

        this.setData({
            haggleId,
            cutId,
        });

        this._init();
    },

    _init() {
        common.initApp({
            loginSuc: () => {
                this._initTabs();
                this._fetch();
                this.$loginSuc();
                this._shareAs = new ShareActionSheet({
                    page: this,
                    scope: 'shareActionSheet'
                });
            }
        });
    },

    _showActionSheet() {
        var {
            haggleId,
            cutId,
        } = this.data;

        this._shareAs.show({
            type: 4,
            actId: haggleId,
            cutId
        });
    },

    /**
     * swiper切换时
     */
    _swiperChange: function(evt) {
        this.setData({
            curSwiperIndex: evt.detail.current,
        });
    },

    /**
     * 预览图片
     */
    _previewImg: function(evt) {
        var formId = evt.detail.formId;
        wx.previewImage({
            current: this.data.imageUrls[this.data.curSwiperIndex],
            urls: this.data.imageUrls,
        })
        common.submitForm(formId);
    },

    _initTabs() {
        var that = this;

        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
                    sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
                });
            }
        });
    },

    tabClick: function(e) {
        var id = e.currentTarget.id;
        var formId = e.detail.formId;

        this.setData({
            sliderOffset: e.currentTarget.offsetLeft,
            activeIndex: id
        });
        common.submitForm(formId);
    },

    /**
     * 根据图片高度设置swiper高度
     */
    _swiperImgLoaded: function(evt) {
        if (this.data.swiperHei > 0) {
            return;
        }
        var self = this;
        var ratio = evt.detail.height / evt.detail.width;

        wx.getSystemInfo({
            success: function(res) {
                self.setData({
                    dataLoaded: true,
                    swiperHei: res.windowWidth * ratio
                });
            }
        });
    },

    /**
     * 预览图片
     */
    _previewImg: function(evt) {
        var formId = evt.detail.formId;
        wx.previewImage({
            current: this.data.imageUrls[this.data.curSwiperIndex],
            urls: this.data.imageUrls,
        })
        common.submitForm(formId);
    },

    _fetch() {
        var self = this;
        var {
            haggleId,
            cutId
        } = this.data;
        ajax.G({
            url: '/market/Activity/showHaggle',
            data: {
                haggle_id: haggleId,
                cut_id: cutId,
            },
            success: (data) => {
                wx.stopPullDownRefresh();

                var result = data.result;
                var {
                    cut_id: cutId,
                    actInfo,
                    goods,
                    actGoodsInfo,
                    ranks,
                    records,
                    joinCount,
                    haggleState,
                    hagglePay,
                    joinHaggle,
                    myHaggle,
                    orderInfo,
                    fromHaggleInfo: fromInfo,
                    lastHaggleInfo: lastInfo,
                } = result;

                self._lastTime = actInfo['left_time'];

                if (goods.detail) {
                    WxParse.wxParse('article', 'html', goods.detail, self, 0);
                }

                self.setData({
                    cutId,
                    bannerType: 0,
                    imageUrls: goods['img_url'].split('|'),
                    goods,
                    actGoodsInfo,
                    actInfo,
                    // ranks,
                    // records,
                    joinCount,
                    haggleState, //砍价状态 0.未完成 1.已完成
                    hagglePay, //是否可以以底价购买
                    joinHaggle, //是否已砍过价
                    myHaggle, //是否是发起人
                    orderInfo,
                    fromInfo,
                    lastInfo,
                });

                self._getList(0);
                self._getList(1);

                if (self._actTimer) {
                    clearTimeout(self._actTimer);
                }
                if (self._lastTime && self._lastTime > 0) {
                    self._actTimerDown();
                }
            },
            fail: () => {
                wx.stopPullDownRefresh();
            }
        });
    },

    /**
     * 砍价
     * @return {[type]} [description]
     */
    _cut(evt) {
        var self = this;
        var {
            mustStart //指定发起砍价
        } = evt.target.dataset;
        var {
            haggleId,
            cutId
        } = this.data;
        var ajaxParams = {
            haggle_id: haggleId,
        };

        if (!mustStart && cutId) {
            ajaxParams.cut_id = cutId;
        }

        ajax.P({
            url: '/market/Activity/joinHaggle',
            data: ajaxParams,
            success: (data) => {
                var result = data.result;

                self.setData({
                    cutId: result.cut_id
                });
                util.alert(result.content);
                self._fetch();
            }
        });
    },

    /**
     * 底价购买
     * @return {[type]} [description]
     */
    _buy() {
        var self = this;
        var {
            haggleId,
            goods,
            actGoodsInfo,
            haggleState,
        } = this.data;

        if (haggleState != 1) {
            return util.alert('还没有砍到底价，赶紧邀请好友帮砍吧');
        }
        var ajaxUrl = '/market/Activity/quickOrder';
        var ajaxParams = {
            act_id: haggleId,
            open_id: app.getOpenId(),
        };

        ajax.P({
            url: ajaxUrl,
            data: ajaxParams,
            success: (data) => {
                var result = data.result;
                var {
                    orderId,
                    wxPayParams
                } = result;
                var wxPayParams = JSON.parse(wxPayParams);
                var orderInfo = this.data.orderInfo || {};

                orderInfo.pay_state = 0;
                orderInfo.order_id = orderId;

                this.setData({
                    orderInfo
                });

                this._paySuccess(wxPayParams);
            }
        });
    },

    /**
     * 再次支付
     */
    _payAgain() {
        var {
            orderInfo = {}
        } = this.data;
        var orderId = orderInfo.order_id;
        if (!orderId) {
            return;
        }
        var params = {
            openId: app.getOpenId(),
            orderId: orderId
        };
        var url = '/market/Activity/doPayAgain';

        ajax.P({
            url: url,
            data: params,
            success: (data) => {
                var result = data.result;
                this._paySuccess(JSON.parse(result.wxPayParams));
            }
        });
    },

    /**
     * 支付成功回调
     */
    _paySuccess(wxPayParams) {
        wxPayParams.success = () => {
            var orderInfo = this.data.orderInfo || {};

            orderInfo.pay_state = 0;
            this.setData({
                orderInfo
            });

            util.alert('支付成功', () => {
                wx.redirectTo({
                    url: '/pages/orderList/index?tabIndex=1'
                });
            });
        }
        wxPayParams.fail = () => {
            wx.redirectTo({
                url: '/pages/orderList/index?tabIndex=1'
            });
        }
        wxUtil.wxPay(wxPayParams);
    },

    /**
     * 倒计时
     * @return {[type]} [description]
     */
    _actTimerDown() {
        var _self = this;
        var sec = _self._lastTime;
        var lastTimeStr = util.getTimeBySec(sec, 'd');

        _self.setData({
            lastTimeStr,
        });
        if (sec == 0) {
            clearTimeout(_self._actTimer);
            _self._fetch();
            return;
        }
        _self._lastTime--;
        _self._actTimer = setTimeout(function() {
            _self._actTimerDown();
        }, 1000)
    },

    /**
     * 总排行榜；出刀记录
     * @param  {[type]} type [0.出刀记录 1.总排行榜]
     * @return {[type]}      [description]
     */
    _getList(type) {
        var _self = this;
        var {
            haggleId,
            cutId,
        } = this.data;
        var pageOrder = +type + 1;
        var url = '/market/Activity/haggleRecords';
        var ajaxParams = {
            haggle_id: haggleId,
        };

        if (type == 1) {
            url = '/market/Activity/haggleRanks';
        } else {
            ajaxParams.cut_id = cutId;
        }

        _self['pagination' + pageOrder] = new Pagination({
            page: this,
            scope: 'page' + pageOrder
        }).init({
            rendData: (page, cb) => {

                ajax.G({
                    url: url,
                    data: ajaxParams,
                    success: (data) => {
                        var result = data.result;
                        var key = type == 0 ? 'records' : 'ranks';
                        var list = _self.data[key] || [];
                        var curList = result[key] || [];
                        var data = {};

                        if (page == 1) {
                            if (pageOrder == 1) {
                                data = {
                                    dataLoaded: true,
                                };
                            }
                            list = curList;
                        } else {
                            list = list.concat(curList)
                        }

                        data[key] = list;

                        _self.setData(data);

                        cb && cb(curList.length);
                    }
                });

            }
        });

    },

    /**
     * 加载更多
     * @return {[type]} [description]
     */
    _loadMore() {
        var _self = this;
        var num = +_self.data.activeIndex + 1;
        var pagination;

        if (_self.data['page' + num].pageEnd) {
            return;
        }

        pagination = _self['pagination' + num];

        pagination && pagination.loadNext();
    },

    /**
     * 展开商品详情
     * @return {[type]} [description]
     */
    _showPanel() {
        this.setData({
            isShowPanel: !this.data.isShowPanel
        })
    },

}));